<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="教师工号" prop="teacherCode">
        <el-input
          v-model="queryParams.teacherCode"
          placeholder="请输入教师工号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职称" prop="titleId">
        <el-select
          v-model="queryParams.titleId"
          placeholder="请选择职称"
          clearable
          style="width: 200px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in teacher_title"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="学历" prop="education">
        <el-select
          v-model="queryParams.degreeId"
          placeholder="请选择学历"
          clearable
          style="width: 200px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in degree"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="学位 ID" prop="degreeId">
        <el-input
          v-model="queryParams.degreeId"
          placeholder="请输入学位 ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="研究领域" prop="researchField">
        <el-input
          v-model="queryParams.researchField"
          placeholder="请输入研究领域"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="所属学院 ID" prop="collegeId">
        <el-input
          v-model="queryParams.collegeId"
          placeholder="请输入所属学院 ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- 搜索表单中的所属学院 -->
      <el-form-item label="所属学院" prop="collegeId">
        <el-select
          v-model="queryParams.collegeId"
          placeholder="请输入学院名称/代码"
          clearable
          filterable
          remote
          :remote-method="filterColleges"
          @change="handleQuery"
          style="width: 200px;"
        >
          <el-option
            v-for="college in filteredColleges"
            :key="college.collegeId"
            :label="`${college.collegeName} (${college.collegeCode})`"
            :value="college.collegeId"
          >
            <span style="float: left">{{ college.collegeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ college.collegeCode }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input
          v-model="queryParams.contactEmail"
          placeholder="请输入联系邮箱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="导师类别" prop="supervisorTypeId">
        <el-select v-model="queryParams.supervisorTypeId" placeholder="请选择导师类别" clearable style="width: 150px;">
          <el-option
            v-for="dict in tutor_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="导师类型" prop="mentorType">
        <el-select v-model="queryParams.mentorType" placeholder="请选择导师类型" clearable style="width:200px;">
          <el-option
            v-for="dict in mentor_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="招生名额" prop="enrollmentQuota">
        <el-input
          v-model="queryParams.enrollmentQuota"
          placeholder="请输入招生名额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作状态" prop="workStatusId">
        <el-select v-model="queryParams.workStatusId" placeholder="请选择工作状态" clearable style="width: 200px;">
          <el-option
            v-for="dict in working_condition"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="导师资格" prop="isSupervisor">
        <el-select v-model="queryParams.isSupervisor" placeholder="请选择是否具备导师资格 ID" clearable style="width: 200px;">
          <el-option
            v-for="dict in y_n"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间" prop="hireDate">
        <el-date-picker clearable
          v-model="queryParams.hireDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入职时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学术头衔" prop="academicTitleId" clearable style="width: 200px;">
        <el-input
          v-model="queryParams.academicTitleId"
          placeholder="请输入学术头衔"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否外聘" prop="foreignTeacher">
        <el-select v-model="queryParams.foreignTeacher" placeholder="请选择是否外聘教师" clearable style="width: 200px;">
          <el-option
            v-for="dict in y_n"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatusId">
        <el-select v-model="queryParams.auditStatusId" placeholder="请选择审核状态 ID" clearable style="width: 200px;">
          <el-option
            v-for="dict in working_condition"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="指导学生数量" prop="studentCount">
        <el-input
          v-model="queryParams.studentCount"
          placeholder="请输入当前指导学生数量"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['teacher:teacher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teacher:teacher:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teacher:teacher:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['teacher:teacher:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学院（部门）名称" align="center" prop="collegeId" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="教师工号" align="center" prop="teacherCode" />
      <el-table-column label="证件类型" align="center" prop="cardType" />
      <el-table-column label="证件号码" align="center" prop="idNumber" />
      <el-table-column label="出生日期" align="center" prop="dateBirth" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="民族" align="center" prop="nationality" />
      <el-table-column label="政治面貌" align="center" prop="politicsStatus" />
      <el-table-column label="学历" align="center" prop="educationBackground" />
      <el-table-column label="学位" align="center" prop="degreeId" />
      <el-table-column label="专业技术职务" align="center" prop="professionalTechnicalPosts" />
<!--      <el-table-column label="性别" align="center">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="gender" :value="scope.row.sex"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="现职称" align="center" prop="currentProfessionalTitle" />
      <el-table-column label="来校年月" align="center" prop="dateOfArrivalSchool" />
      <el-table-column label="从教年月" align="center" prop="dateOfArrivalSchool" />
      <el-table-column label="教职工类别" align="center" prop="facultyStaffCategory" />
<!--      <el-table-column label="职称" align="center">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="teacher_title" :value="scope.row.titleId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="学位" align="center"> &lt;!&ndash; 列表列 &ndash;&gt;-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="degree" :value="scope.row.degreeId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="联系电话" align="center" prop="contactPhone" />
<!--      <el-table-column label="导师类别" align="center" prop="supervisorTypeId">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="tutor_category" :value="scope.row.supervisorTypeId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="导师类型" align="center" prop="mentorType">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="mentor_type" :value="scope.row.mentorType"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="招生名额" align="center" prop="enrollmentQuota" />-->
<!--      <el-table-column label="工作状态" align="center" prop="workStatusId">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="working_condition" :value="scope.row.workStatusId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="是否具备导师资格" align="center" prop="isSupervisor">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="y_n" :value="scope.row.isSupervisor"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="入职时间" align="center" prop="hireDate" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="学术头衔" align="center" prop="academicTitleId" />-->
<!--      <el-table-column label="是否外聘教师" align="center" prop="foreignTeacher">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="y_n" :value="scope.row.foreignTeacher"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="审核状态" align="center" prop="auditStatusId">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="working_condition" :value="scope.row.auditStatusId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <!-- <el-table-column label="主讲课程 ID 列表" align="center" prop="teachingCourses" /> -->
<!--      <el-table-column label="主讲课程" align="center">-->
<!--        <template #default="scope">-->
<!--          <span>{{ getCourseNames(scope.row.teachingCourses) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="当前指导学生数量" align="center" prop="studentCount" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['teacher:teacher:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['teacher:teacher:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.titleImport" v-model="upload.openImport" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
          @change="handleFileChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center">
          <div>
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="handleCancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改教师信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="teacherRef" :model="form" :rules="rules" label-width="80px">
        <!-- 教师工号 -->
        <el-form-item label="教师工号" prop="teacherCode">
          <el-input v-model="form.teacherCode" placeholder="请输入教师工号" />
        </el-form-item>
        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <!-- 证件类型 -->
        <el-form-item label="证件类型" prop="cardType">
          <el-input v-model="form.cardType" placeholder="请输入证件类型" />
        </el-form-item>
        <!-- 证件号码 -->
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <!-- 出生日期 -->
        <el-form-item label="出生日期" prop="dateBirth">
          <el-date-picker
              v-model="form.dateBirth"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择出生日期"
          />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option v-for="dict in gender" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 民族 -->
        <el-form-item label="民族" prop="nationality">
          <el-input v-model="form.nationality" placeholder="请输入民族" />
        </el-form-item>
        <!-- 政治面貌 -->
        <el-form-item label="政治面貌" prop="politicsStatus">
          <el-input v-model="form.politicsStatus" placeholder="请输入政治面貌" />
        </el-form-item>
        <!-- 学历 -->
        <el-form-item label="学历" prop="educationBackground">
          <el-input v-model="form.educationBackground" placeholder="请输入学历" />
        </el-form-item>
        <!-- 学位 -->
        <el-form-item label="学位" prop="degreeId">
          <el-input v-model="form.degreeId" placeholder="请输入学位" />
        </el-form-item>
        <!-- 专业技术职务 -->
        <el-form-item label="专业技术职务" prop="professionalTechnicalPosts">
          <el-input v-model="form.professionalTechnicalPosts" placeholder="请输入专业技术职务" />
        </el-form-item>
        <!-- 现职称 -->
        <el-form-item label="现职称" prop="currentProfessionalTitle">
          <el-input v-model="form.currentProfessionalTitle" placeholder="请输入现职称" />
        </el-form-item>
        <!-- 来校年月 -->
        <el-form-item label="来校年月" prop="dateOfArrivalSchool">
          <el-date-picker
              v-model="form.dateOfArrivalSchool"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择来校年月"
          />
        </el-form-item>
        <!-- 从教年月 -->
        <el-form-item label="从教年月" prop="teachingYears">
          <el-date-picker
              v-model="form.teachingYears"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择从教年月"
          />
        </el-form-item>
        <!-- 教职工类别 -->
        <el-form-item label="教职工类别" prop="facultyStaffCategory">
          <el-input v-model="form.facultyStaffCategory" placeholder="请输入教职工类别" />
        </el-form-item>
        <!-- 所属学院（学院名称回显） -->
        <el-form-item label="所属学院" prop="collegeId">
          <el-select
              v-model="form.collegeId"
              placeholder="请选择所属学院"
              clearable
              filterable
              remote
              :remote-method="filterColleges"
              style="width: 100%;"
              :loading="collegeLoading"
          >
            <el-option
                v-for="college in filteredColleges"
                :key="college.collegeId"
                :label="`${college.collegeName} (${college.collegeCode})`"
                :value="college.collegeId"
            >
              <span style="float: left">{{ college.collegeName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ college.collegeCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 联系电话 -->
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Teacher">
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher,importteacherData } from "@/api/teacher/teacher";
import { listCollege, getCollege } from "@/api/college/college";
import { listCourse } from "@/api/course/course";
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue';
import { debounce } from 'lodash';
import { getToken } from "@/utils/auth";
import { listDept } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { addUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { mentor_type, working_condition, y_n, tutor_category,teacher_title,degree,gender} = proxy.useDict('mentor_type', 'working_condition', 'y_n', 'tutor_category','teacher_title','degree','gender');
// const titleMap = new Map(teacher_title.map(item => [parseInt(item.value), item.label]));
const teacherList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teacherCode: null,
    name: null,
    sex: null,
    titleId: null,
    degreeId: null,
    researchField: null,
    collegeId: null,
    contactEmail: null,
    contactPhone: null,
    supervisorTypeId: null,
    mentorType: null,
    enrollmentQuota: null,
    workStatusId: null,
    isSupervisor: null,
    hireDate: null,
    academicTitleId: null,
    foreignTeacher: null,
    auditStatusId: null,
    teachingCourses: null,
    studentCount: null
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    collegeId: [
      { required: true, message: "请选择所属学院", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询教师信息列表 */
function getList() {
  loading.value = true;
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 导入相关配置
const upload = ref({
  titleImport: "",
  openImport: false,
  isUploading: false,
  updateSupport: false,
  headers: {
    Authorization: "Bearer " + getToken()
  },
  url: "/teacher/teacher/importteacherData",
});

/** 打开导入对话框 */
function handleImport() {
  console.log('准备打开导入对话框');
  upload.value.isUploading = false;
  upload.value.updateSupport = false;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  upload.value.titleImport = "导入课程信息表";
  upload.value.openImport = true;
  console.log('导入对话框状态:', upload.value.openImport);
}

/** 关闭导入对话框 */
function handleCancelImport() {
  console.log('关闭导入对话框');
  upload.value.openImport = false;
  upload.value.isUploading = false;
  importFile.value = null;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
}

/** 下载导入模板 */
function importTemplate() {
  proxy.download(
      import.meta.env.VUE_APP_BASE_API + '/teacher/teacher/exportTemplate',
      {
        ...queryParams.value
      },
      `课程信息模板${new Date().getTime()}.xlsx`
  );
}

/** 文件上传进度处理 */
function handleFileUploadProgress(event, file, fileList) {
  console.log('===== 上传进度 =====');
  console.log('进度百分比:', Math.round(event.percent) + '%');
  console.log('当前文件:', file.name);
  upload.value.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  console.log('===== 上传成功 =====');
  console.log('后端响应内容:', response);
  console.log('上传成功的文件:', file.name);
  upload.value.openImport = false;
  upload.value.isUploading = false;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  proxy.$alert(response.msg, "导入结果", {
    dangerouslyUseHTMLString: true
  });
  getList();
}

/** 提交上传文件（执行导入） */
function submitFileForm() {
  if (!importFile.value) {
    proxy.$message.warning('请选择要上传的文件');
    return;
  }

  console.log('使用保存的文件:', importFile.value.name);
  console.log('updateSupport参数:', upload.value.updateSupport);

  upload.value.isUploading = true;
  importteacherData(importFile.value, upload.value.updateSupport)
      .then(async response => {
        upload.value.isUploading = false;
        upload.value.openImport = false;
        importFile.value = null;
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
        proxy.$message.success(response.msg || '导入成功');
        getList();

        // 导入成功后，自动创建用户账户
        await createUsersAfterImport();
      })
      .catch(error => {
        upload.value.isUploading = false;
        console.error('上传失败:', error);
        proxy.$message.error('上传失败: ' + (error.message || '未知错误'));
      });
}

// 新增：导入完成后创建用户功能
async function createUsersAfterImport() {
  try {
    proxy.$modal.confirm('是否为导入的教师创建系统用户账户？').then(async () => {
      // 显示加载状态
      const loadingInstance = proxy.$loading({
        lock: true,
        text: '正在创建用户账户...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 获取所有教师数据
        let allTeachers = [];
        let pageNum = 1;
        const pageSize = 100; // 每页获取100条数据
        let hasMore = true;

        // 分页获取所有数据
        while (hasMore) {
          const response = await listTeacher({
            pageNum: pageNum,
            pageSize: pageSize
          });

          // 将当前页数据添加到总数据中
          allTeachers = allTeachers.concat(response.rows);

          // 判断是否还有更多数据
          if (response.rows.length < pageSize || allTeachers.length >= response.total) {
            hasMore = false;
          }

          pageNum++;
        }

        const teachers = allTeachers;
        let successCount = 0;
        let failureCount = 0;
        let failedTeachers = []; // 记录失败的教师

        // 预先获取部门和角色信息
        const deptResponse = await listDept();
        const roleResponse = await listRole({ roleName: '老师' });

        // 为每个教师创建用户账户
        for (let i = 0; i < teachers.length; i++) {
          const teacher = teachers[i];

          try {
            // 检查是否已存在同用户名的用户
            // 使用已有的API方法而不是直接调用proxy.$http
            // 这里我们跳过检查，直接尝试创建，让后端处理重复用户的情况

            let deptId = null;

            if (deptResponse.data && deptResponse.data.length > 0) {
              // 1. 根据教师信息中的学院名称找到对应的学院部门
              // 修正字段名：使用collegeName而不是coll
              const collegeDept = deptResponse.data.find(dept => dept.deptName === teacher.collegeId);

              if (collegeDept) {
                // 2. 使用该学院部门ID在ancestors字段中查找包含该ID的数据
                // 3. 在这些数据中查找deptName为"教师"的部门
                const teacherDept = deptResponse.data.find(dept =>
                    dept.ancestors.includes(collegeDept.deptId) &&
                    dept.deptName === '老师'
                );

                // 如果找到了教师部门，则使用教师部门ID
                // 否则不分配部门（根据要求不能回退到学院部门）
                if (teacherDept) {
                  deptId = teacherDept.deptId;  // 修改为deptId而不是collegeId
                }
              }
            }

            let roleId = null;
            if (roleResponse.rows && roleResponse.rows.length > 0) {
              // 找到完全匹配的角色
              const matchedRole = roleResponse.rows.find(role => role.roleName === '老师');
              if (matchedRole) {
                roleId = matchedRole.roleId;
              }
            }

            // 如果没有找到部门或角色，记录错误并继续
            if (!deptId || !roleId) {
              failureCount++;
              failedTeachers.push({
                name: teacher.name,
                code: teacher.teacherCode,
                reason: !deptId ? '未找到对应部门' : '未找到教师角色'
              });
              continue;
            }

            // 创建用户
            const userData = {
              userName: teacher.teacherCode,
              nickName: teacher.name,
              password: '123456',
              deptId: deptId,
              roleIds: [roleId]
            };

            // 使用已导入的addUser方法而不是直接调用proxy.$http
            await addUser(userData);
            console.log(`${teacher.name} 用户创建成功`);
            successCount++;

          } catch (error) {
            console.error(`为教师 ${teacher.name} 创建用户时出错:`, error);
            failureCount++;
            failedTeachers.push({
              name: teacher.name,
              code: teacher.teacherCode,
              reason: error.message || '创建用户时发生错误'
            });
          }
        }

        // 关闭加载状态
        loadingInstance.close();

        // 显示结果
        if (failureCount === 0) {
          proxy.$modal.msgSuccess(`用户创建完成，成功创建 ${successCount} 个用户`);
        } else {
          let message = `用户创建完成，成功: ${successCount}，失败: ${failureCount}`;
          if (failedTeachers.length > 0) {
            const failedList = failedTeachers.map(t => `${t.name}(${t.code}): ${t.reason}`).join('\n');
            message += `\n\n失败列表:\n${failedList}`;
          }
          proxy.$modal.msgWarning(message);
        }

      } catch (error) {
        loadingInstance.close();
        console.error("批量用户创建失败:", error);
        proxy.$modal.msgError("批量用户创建失败: " + (error.message || "未知错误"));
      }
    }).catch(() => {
      // 用户选择不创建账户
      console.log('用户取消创建账户');
    });
  } catch (error) {
    console.error("创建用户过程出错:", error);
    proxy.$modal.msgError("创建用户过程出错: " + (error.message || "未知错误"));
  }
}


/** 文件上传失败处理 */
function handleFileError(err, file, fileList) {
  console.error('===== 上传错误详情 =====');
  console.error('错误对象:', err);
  console.error('请求URL:', upload.value.url + '?updateSupport=' + upload.value.updateSupport);
  console.error('响应状态码:', err.response?.status);
  console.error('响应内容:', err.response?.data);
  console.error('错误消息:', err.message);
  upload.value.isUploading = false;
  proxy.$message.error('上传失败: ' + (err.message || '未知错误'));
}

/** 文件选择变化时保存文件引用 */
function handleFileChange(file, fileList) {
  console.log('选择的文件:', file);
  console.log('文件列表:', fileList);
  importFile.value = file.raw || file;
}

const uploadRef = ref(null);
const importFile = ref(null);

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    uuid: null,
    teacherCode: null,
    name: null,
    sex: null,
    titleId: null,
    degreeId: null,
    researchField: null,
    collegeId: null,
    contactEmail: null,
    contactPhone: null,
    supervisorTypeId: null,
    mentorType: null,
    enrollmentQuota: null,
    workStatusId: null,
    isSupervisor: null,
    hireDate: null,
    academicTitleId: null,
    foreignTeacher: null,
    auditStatusId: null,
    teachingCourses: null,
    studentCount: null
  };
  proxy.resetForm("teacherRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.uuid);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加教师信息";
}

// /** 修改按钮操作 */
// async function handleUpdate(row) {
//   reset();
//   try {
//     const res = await getTeacher(row.uuid);
//     form.value = res.data;

//     // 确保学院数据加载
//     const collegeRes = await listCollege({ pageSize: 1000 });
//     const collegeList = collegeRes.rows;

//     // 处理学院名称回显
//     if (res.data.collegeId) {
//       const college = collegeList.find(
//         c => c.collegeId === res.data.collegeId
//       );
//       if (college) {
//         form.value._collegeName = college.collegeName;
//       }
//     }

//     open.value = true;
//     title.value = "修改教师信息";
//   } catch (err) {
//     console.error('获取详情失败:', err);
//     proxy.$modal.msgError("数据加载失败");
//   }
// }
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  try {
    const res = await getTeacher(row.uuid);
    form.value = res.data;
    // 确保 teachingCourses 不包含 null 值
    form.value.teachingCourses = res.data.teachingCourses 
      ? res.data.teachingCourses.split(',').filter(item => item!== null && item!== '') 
      : [];

    // 确保学院数据加载
    const collegeRes = await listCollege({ pageSize: 1000 });
    const collegeList = collegeRes.rows;

    // 处理学院名称回显
    if (res.data.collegeId) {
      const college = collegeList.find(
        c => c.collegeId === res.data.collegeId
      );
      if (college) {
        form.value._collegeName = college.collegeName;
      }
    }

    open.value = true;
    title.value = "修改教师信息";
  } catch (err) {
    console.error('获取详情失败:', err);
    proxy.$modal.msgError("数据加载失败");
  }
}

// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["teacherRef"].validate(valid => {
//     if (valid) {
//       if (form.value.uuid != null) {
//         updateTeacher(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addTeacher(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }

// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["teacherRef"].validate(valid => {
//     if (valid) {
//       // 确保 teachingCourses 是字符串
//       if (Array.isArray(form.value.teachingCourses)) {
//         form.value.teachingCourses = form.value.teachingCourses.join(',');
//       }
//       if (form.value.uuid != null) {
//         updateTeacher(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addTeacher(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }
/** 提交按钮 */
function submitForm() {
  proxy.$refs["teacherRef"].validate(valid => {
    if (valid) {
      // 过滤无效值并转换为逗号分隔字符串
      if (Array.isArray(form.value.teachingCourses)) {
        form.value.teachingCourses = form.value.teachingCourses
          .filter(item => item !== null && item !== '')
          .join(',');
      }
      if (form.value.uuid != null) {
        updateTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
         // 打印待提交的数据
      console.log("提交表单数据:", JSON.stringify(form.value, null, 2));
      } else {
        addTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _uuids = row.uuid || ids.value;
  proxy.$modal.confirm('是否确认删除教师信息编号为"' + _uuids + '"的数据项？').then(function() {
    return delTeacher(_uuids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teacher/teacher/export', {
    ...queryParams.value
  }, `teacher_${new Date().getTime()}.xlsx`)
}
// 新增响应式数据
const collegeList = ref([]);
const filteredColleges = ref([]);
const collegeLoading = ref(false);
const courseList = ref([]);
const filteredCourses = ref([]);
const courseLoading = ref(false);
// 获取学院列表
const getCollegeList = async () => {
  try {
    const res = await listCollege({ pageSize: 1000 }); // 假设支持分页查询所有学院
    collegeList.value = res.rows;
    filteredColleges.value = res.rows;
  } catch (err) {
    console.error('学院数据加载失败:', err);
    proxy.$modal.msgError("学院列表加载失败");
  }
};
// 获取课程列表
const getCourseList = async () => {
  try {
    const res = await listCourse({ pageSize: 100000 }); // 假设支持分页查询所有课程
    courseList.value = res.rows;
    filteredCourses.value = res.rows;
  } catch (err) {
    console.error('课程数据加载失败:', err);
    proxy.$modal.msgError("课程列表加载失败");
  }
};
// 学院过滤方法
const filterColleges = debounce((query) => {
  collegeLoading.value = true;
  try {
    if (query) {
      const lowerQuery = query.toLowerCase();
      filteredColleges.value = collegeList.value.filter(college => 
        college.collegeName?.toLowerCase().includes(lowerQuery) ||
        college.collegeCode?.includes(query)
      );
    } else {
      filteredColleges.value = collegeList.value;
    }
  } finally {
    collegeLoading.value = false;
  }
}, 300);
// 课程过滤方法
const filterCourses = debounce((query) => {
  courseLoading.value = true;
  try {
    if (query) {
      const lowerQuery = query.toLowerCase();
      filteredCourses.value = courseList.value.filter(course => 
        course.courseName?.toLowerCase().includes(lowerQuery)
      );
    } else {
      filteredCourses.value = courseList.value;
    }
  } finally {
    courseLoading.value = false;
  }
}, 300);

// 学院名称解析方法
const getCollegeName = (collegeId) => {
  if (!collegeId) return '-';
  const college = collegeList.value.find(c => c.collegeId === collegeId);
  return college ? `${college.collegeName} (${college.collegeCode})` : '未知学院';
};
// 课程名称解析方法
const getCourseNames = (courseIds) => {
  if (!courseIds) return '-';
  const ids = courseIds.split(',');
  const names = ids.map(id => {
    const course = courseList.value.find(c => c.uuid === id);
    return course ? course.courseName : '未知课程';
  });
  return names.join(', ');
};
// 初始化时加载学院和课程数据
onMounted(() => {
  getCollegeList();
  getCourseList();
  getList();
  console.log(degree);
});
</script>    